import { CommonModule } from '@angular/common';
import type { OnDestroy, OnInit } from '@angular/core';
import { Component } from '@angular/core';
import type { BuilderContent } from '@builder.io/sdk-angular';
import {
  fetchOneEntry,
  isPreviewing,
  subscribeToEditor,
} from '@builder.io/sdk-angular';

@Component({
  standalone: true,
  selector: 'app-live-preview',
  imports: [CommonModule],
  template: `
    <div *ngIf="loading">Loading Data...</div>

    <div *ngIf="!loading && !notFound" class="blog-data-preview">
      <div>Blog Title: {{ content!.data?.title }}</div>
      <div>Authored by: {{ content!.data?.['author'] }}</div>
      <div>Handle: {{ content!.data?.['handle'] }}</div>
    </div>
    <div *ngIf="notFound">404 - Content not found</div>
  `,
})
export class LivePreviewComponent implements OnInit, OnDestroy {
  content: BuilderContent | null = null;
  loading = true;
  notFound = false;

  private unsubscribeFn: () => void = () => {};

  ngOnInit(): void {
    fetchOneEntry({
      model: 'blog-data',
      apiKey: 'ee9f13b4981e489a9a1209887695ef2b',
      userAttributes: { urlPath: window.location.pathname },
    })
      .then((data) => {
        this.content = data;
        this.notFound = !this.content && !isPreviewing();
      })
      .finally(() => {
        this.loading = false;
      });

    this.unsubscribeFn = subscribeToEditor({
      model: 'blog-data',
      apiKey: 'ee9f13b4981e489a9a1209887695ef2b',
      callback: (updatedContent) => {
        this.content = updatedContent;
        this.notFound = !this.content && !isPreviewing();
      },
    });
  }

  ngOnDestroy(): void {
    if (this.unsubscribeFn) {
      this.unsubscribeFn();
    }
  }
}
